package week03.question01.gateway01;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import week03.question01.gateway01.httpclient.HttpClientDemo;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

public class HttpHandler extends ChannelInboundHandlerAdapter {

    private String targetHttpServerUri;

    public HttpHandler(String targetHttpServerUri) {
        this.targetHttpServerUri = targetHttpServerUri;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        String uri = fullHttpRequest.uri();

        String response = HttpClientDemo.doGet(targetHttpServerUri + uri.substring(1));
        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(response.getBytes("UTF-8")));
        defaultFullHttpResponse.headers().set("Content-Type","application/json");
        defaultFullHttpResponse.headers().setInt("Content-Length", defaultFullHttpResponse.content().readableBytes());
        ctx.write(defaultFullHttpResponse).addListener(ChannelFutureListener.CLOSE);
    }
}
